package com.dragon.mmochat.util;

import java.io.*;

public class SystemInfo {
	public static long maxThreadParam = 0; // 线程数/页面响应时间 的最大值
	public static long bestThreadNum = 0; // 当maxThreadParam取得最大值时的线程数,即最优线程数
	public static long bestResponseTime = 0; // 当maxThreadParam取得最大值时的页面响应时间
	public static int bestOnlinePlayerNum = 0; // 当maxThreadParam取得最大值时的在线人数

	/**
	 * 获取cpu使用情况
	 * 
	 * @return
	 * @throws Exception
	 */
	public static double getCpuUsage() throws Exception {
		double cpuUsed = 0;

		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// 调用系统的“top"命令

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			String[] strArray = null;

			// 过滤其它信息
			while ((str = in.readLine()) != null) {
				boolean find = false;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					if (tmp.equals("PID")) {
						find = true;
						break;
					}
				}
				if (find) {
					break;
				}
			}
			while ((str = in.readLine()) != null) {
				int m = 0;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					if (++m == 9) {// 第9列为CPU的使用百分比(RedHat
						cpuUsed += Double.parseDouble(tmp);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}
		return cpuUsed;
	}

	/**
	 * 内存监控
	 * 
	 * @return
	 * @throws Exception
	 */
	public static double getMemUsage() throws Exception {

		double menUsed = 0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("top -b -n 1");// 调用系统的“top"命令

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			String[] strArray = null;

			// 过滤其它信息
			while ((str = in.readLine()) != null) {
				boolean find = false;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					if (tmp.equals("PID")) {
						find = true;
						break;
					}
				}
				if (find) {
					break;
				}
			}
			while ((str = in.readLine()) != null) {
				int m = 0;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					if (++m == 10) {
						// 9)--第10列为mem的使用百分比(RedHat 9)
						menUsed += Double.parseDouble(tmp);
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}
		return menUsed;
	}

	/**
	 * 获取磁盘空间大小
	 * 
	 * @return
	 * @throws Exception
	 */
	public static double getDeskUsage() throws Exception {
		double totalHD = 0;
		double usedHD = 0;
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("df -hl");// df -hl 查看硬盘空间

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			String[] strArray = null;
			// 过滤其它信息
			while ((str = in.readLine()) != null) {
				boolean find = false;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					if (tmp.equals("Filesystem")) {
						find = true;
						break;
					}
				}
				if (find) {
					break;
				}
			}

			while ((str = in.readLine()) != null) {
				int m = 0;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0)
						continue;
					++m;
					if (tmp.indexOf("G") != -1) {
						if (m == 2) {
							if (!tmp.equals("") && !tmp.equals("0"))
								totalHD += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1)) * 1024;

						}
						if (m == 3) {
							if (!tmp.equals("none") && !tmp.equals("0"))
								usedHD += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1)) * 1024;

						}
					}
					if (tmp.indexOf("M") != -1) {
						if (m == 2) {
							if (!tmp.equals("") && !tmp.equals("0"))
								totalHD += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1));

						}
						if (m == 3) {
							if (!tmp.equals("none") && !tmp.equals("0"))
								usedHD += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1));
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
		}
		return (usedHD / totalHD) * 100;
	}

	public static int getTotalMem() throws Exception {
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("free");

		BufferedReader in = null;
		try {
			String[] strArray = null;
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			in.readLine();
			String str = in.readLine();
			if (str != null && str.length() > 0) {
				strArray = str.split(" ");
				int m = 0;
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0) {
						continue;
					}
					m++;
					if (m == 2) {
						return Integer.parseInt(tmp);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static int getThreadNum() {
		try {
			String processName = java.lang.management.ManagementFactory
					.getRuntimeMXBean().getName();
			long pid = Long.parseLong(processName.split("@")[0]);

			Runtime rt = Runtime.getRuntime();
			Process p = rt.exec("cat /proc/" + pid + "/status");
			if (p == null) {
				return 0;
			}
			BufferedReader in = null;
			try {
				in = new BufferedReader(new InputStreamReader(p
						.getInputStream()));
				if (in == null) {
					return 0;
				}
				String str;
				while ((str = in.readLine()) != null) {
					if (str == null || str.trim().length() == 0) {
						continue;
					}
					if (str.startsWith("Threads")) {
						return Integer.parseInt(str.substring(8).trim());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String getInfo() {
		String info = "";
		try {
			int totalMem = getTotalMem() / 1024;// MB
			Runtime lRuntime = Runtime.getRuntime();
			long totalJVMMem = lRuntime.totalMemory() / 1024 / 1024;
			long freeJVMMem = lRuntime.freeMemory() / 1024 / 1024;

			info += "------------系统监控------------<br/>";
			info += "CPU使用率:" + (int) getCpuUsage() + "%<br/>";
			info += "物理内存使用率:" + (int) getMemUsage() + "%<br/>";
			info += "总内存:" + totalMem + "MB,剩余内存:"
					+ (int) (totalMem * (100 - getMemUsage()) / 100)
					+ "MB<br/>";
			info += "硬盘使用率:" + (int) getDeskUsage() + "%<br/><br/>";

			info += "------------jvm监控-------------<br/>";
			info += "JVM可用内存上限:" + lRuntime.maxMemory() / 1024 / 1024
					+ "MB<br/>";
			info += "JVM已申请的内存:" + totalJVMMem + "MB<br/>";
			info += "JVM已申请内存中已使用的内存:" + (totalJVMMem - freeJVMMem) + "MB<br/>";
			info += "JVM已申请内存中未使用的内存:" + freeJVMMem + "MB<br/>";
			info += "Available Processors :" + lRuntime.availableProcessors();
		} catch (Exception e) {
			info = e.getMessage();
		}
		return info;
	}

	public static void setThreadParam(long curThreadParam, long curThreadNum,
			long curResponseTime, int curPlayerNum) {
		if (curThreadParam > maxThreadParam) {
			maxThreadParam = curThreadParam;
			bestThreadNum = curThreadNum;
			bestResponseTime = curResponseTime;
			bestOnlinePlayerNum = curPlayerNum;
		}
	}
}
